// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../../../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 是否使用窗口
const useWindow = true;
// ✅ 窗口大小
const windowSize = 5;

// ✅ 预测结果记录
const predictResults = [];
let correct = 0;
let maxWrongStreak = 0;
let currentWrongStreak = 0;

// ✅ 最近最大间隔策略函数
const recentMaxGapStrategy = (temp) => {
  const history = temp.map((item) => item.number);
  const lastIndexMap = new Map(); // 存储号码上次出现的索引
  const gaps = []; // 每个号码的最近间隔

  for (let i = history.length - 1; i >= 0; i--) {
    const num = history[i];
    if (lastIndexMap.has(num)) {
      const gap = lastIndexMap.get(num) - i;
      gaps.push({ number: num, gap });
      lastIndexMap.set(num, i);
    } else {
      lastIndexMap.set(num, i);
    }
  }

  // 去重并排序，间隔越大优先
  const uniqueSorted = _.uniqBy(_.orderBy(gaps, "gap", "desc"), "number");

  // 提取最多 32 个号码
  const selected = uniqueSorted.slice(0, 32).map((item) => item.number);

  // 若不足 32 个，用未出现过的补足
  const selectedSet = new Set(selected);
  for (const n of allNumbers) {
    if (selectedSet.size >= 32) break;
    if (!selectedSet.has(n)) selectedSet.add(n);
  }

  const result = Array.from(selectedSet);

  if (result.length !== 32) {
    throw new Error(`❗ 无法生成 32 个不重复号码（目前只有 ${result.length} 个）`);
  }

  return result;
};

// ✅ 主循环：遍历每一期数据
allValues.forEach((item, index) => {
  const temp = useWindow
    ? allValues.slice(Math.max(0, index - windowSize), index)
    : allValues.slice(0, index);

  if (temp.length === 0) return;

  const selectedNumbers = recentMaxGapStrategy(temp);

  // ✅ 判断是否命中
  try {
    const isHit = checkAccuracy(selectedNumbers, item.number);
    if (isHit) {
      correct += 1;
      currentWrongStreak = 0;
    } else {
      currentWrongStreak += 1;
      maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
    }
    predictResults.push(selectedNumbers);
  } catch (err) {
    console.error(`❌ checkAccuracy error at index ${index}: ${err.message}`);
  }
});

// ✅ 输出统计结果
const total = predictResults.length;
const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);
